﻿// The base class for all the validators
define([
    'Wjs/Wjs',
    'Wjs/ui/widgets/validation/validatorManager'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'Validator',

        internal: {

            initialize: function () {

                this.validateOnBlur = true;

                this.setMessage(this.message);
            }
        },

        // The regular expression to test against
        regex: null,

        // The error message to display on error
        message: 'Validation failed for field: [${fieldName}]',

        setValidateOnBlur: function(validate) {

            this.validateOnBlur = validate;

            return this;
        },

        setMessage: function (message) {

            this.template = Wjs.compile(message);

            return this;
        },

        // The validation function
        validate: function (field, validationContext) {
            var value = field.getValue(),
                match = true;

            if (this.regex) {

                match = this.regex.test(value);

                if (!match) {

                    this.handleError(field, validationContext);
                }

                return match;
            }
        },

        formatError: function (field) {

            return this.template({
                fieldName: field.display || field.getName()
            });
        },

        handleError: function (field, validationContext) {

            var errorMessage = this.formatError(field);

            if (validationContext.validationSummary) { // Provide a summary of the validation errors

                validationContext.errors.push({
                    error: errorMessage
                });
            }
            else { // Show errors on field

                throw 'Not implemented';
            }
        }

    });

});